package priv.mill.generator.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import priv.mill.db.NameUtils;

public class FreemarkerUtil {
	private static interface Inner{
		FreemarkerUtil INSTANCE = new FreemarkerUtil();
	}
	private FreemarkerUtil() {}
	public static FreemarkerUtil instance() {
		return Inner.INSTANCE;
	}
	private static final String FTL = "/ftl";
	private static final String MYTEMPLATE = "Mytemplate";

	private Template getTemplate(String name, Class<?> clzz) throws IOException {
		// 通过Freemaker的Configuration读取相应的ftl
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_19);
		// 设定去哪里读取相应的ftl模板文件
		cfg.setClassForTemplateLoading(clzz, FTL);
		// 在模板文件目录中找到名称为name的文件
		Template temp = cfg.getTemplate(name);
		return temp;
	}
	
	private Template getTemplate(File path,String name, Class<?> clzz) throws IOException {
		// 通过Freemaker的Configuration读取相应的ftl
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_19);
		// 设定去哪里读取相应的ftl模板文件
		cfg.setDirectoryForTemplateLoading(path);
		// 在模板文件目录中找到名称为name的文件
		Template temp = cfg.getTemplate(name);
		return temp;
	}

	private Template getStringTemplate(String contet) throws IOException {
		Configuration cfg = new Configuration(Configuration.VERSION_2_3_19);
		StringTemplateLoader templateLoader = new StringTemplateLoader();
		templateLoader.putTemplate(MYTEMPLATE, contet);
		cfg.setTemplateLoader(templateLoader);
		return cfg.getTemplate(MYTEMPLATE);
	}

	public static void main(String[] args) throws IOException, TemplateException {
		Map<String,Object> map = new HashMap<>();
		map.put("user", "mill");
		String parse = FreemarkerUtil.instance().parse("test.ftl",map);
		System.out.println(parse);
	}
	public String parse(String name, Map<String, Object> map) throws IOException, TemplateException {
		Template template = getTemplate(name, getClass());
		try(ByteArrayOutputStream out2 = new ByteArrayOutputStream();
				Writer out = new OutputStreamWriter(out2);){
			template.process(map, out);
			return new String(out2.toByteArray());
		}
	}
	public void toFile(String name, Map<String, Object> map,File dist) throws IOException, TemplateException {
		Template template = getTemplate(name, getClass());
		try(Writer out = new FileWriter(dist);){
			template.process(map, out);
		}
	}

	
}